import json

from docx import Document

from ai import AIHandle
from command import CommandExcute


# 获取巡检信息文档
def getInspectionDocx(need_to_dict, commandResult, docFilePath, fixedFilePath, newFilePath, aiParamsPath):
    # 定义要替换的占位符和对应的数据
    replacements = {}
    # replaceMents 加入 need_to_dict
    for key, value in need_to_dict.items():
        replacements.setdefault('$' + str(key) + '$', value)
    doc = Document(docFilePath)
    with open(fixedFilePath, 'r', encoding='utf-8') as f:
        commandParams = json.load(f)
        # 处理固定巡检命令
    fixedCommand = commandParams.get('fixedInfo')
    # 填充固定的参数
    for key, value in fixedCommand.items():
        replacements.setdefault('$' + str(key) + '$', value)
    # 填充巡检信息参数
    inspectionResult = ''
    for key, value in commandResult.items():
        inspectionResult += key + ' : ' + value + '\n'
        # 将 key, value 组装成字符串，存入 result ，用于后续的AI 结果分析
        valueFlag = True
        if value == '':
            valueFlag = False
            value = '未查询到相关信息'
        replacements.setdefault('$' + str(key) + '$', value)
        # 引入AI 对巡检结果进行分析，获取结果输出到_trans 中
        if valueFlag:
            transParams = CommandExcute.getNeedTranslationInfo(aiParamsPath)
            if key in transParams:
                premise = str(transParams.get(key))
                value = AIHandle.getAIResult(premise + '\n' + value)
                replacements.setdefault('$' + str(key) + '_trans$', value)
        else:
            replacements.setdefault('$' + str(key) + '_trans$', '')
    # 针对结果进行分析
    aiParams = CommandExcute.getAIInfo(aiParamsPath)
    for key, value in aiParams.items():
        if aiParams.get('inspectionResult'):
            premise = str(aiParams.get('inspectionResult'))
            value = AIHandle.getAIResult(premise + '\n' + inspectionResult)
            replacements.setdefault('$' + str(key) + '_AI$', value)
        else:
            # 直接通过AI 分析处理 给出结果
            premise = str(aiParams.get(key))
            value = AIHandle.getAIResult(premise)
            replacements.setdefault('$' + str(key) + '_AI$', value)

    print("replacements")
    print(replacements)
    replace_text(doc, replacements)
    # 保存新的文档
    doc.save(newFilePath)


# 替换文档中的占位符
def replace_text(doc, replacements):
    # 遍历文档中的所有段落和运行，查找并替换占位符
    getText(doc, replacements)
    # 遍历文档中的所有表格和单元格，查找并替换占位符
    for table in doc.tables:
        for row in table.rows:
            for cell in row.cells:
                getText(cell, replacements)
    # 遍历所有形状，查找文本框并替换占位符
    for shape in doc.inline_shapes:
        getText(shape.text_frame, replacements)


def getText(cell, replacements):
    for paragraph in cell.paragraphs:
        for run in paragraph.runs:
            # run.font.name = '宋体'
            # run.font.size = Pt(12)
            # run.font.bold = False
            for placeholder, data in replacements.items():
                if placeholder in run.text:
                    run.text = run.text.replace(placeholder, data)
